<template>
  <div class="container-big wing-blank signin-page">
    <!-- <div class="alibaba-design" /> -->
    <!-- <img class="ucan-image" src="https://gw.alicdn.com/tfs/TB1ExhcHxnaK1RjSZFBXXcW7VXa-1392-800.png"> -->
    <div class="signin-form">
      <co-input v-model="mobile" @focus="focusIntoView" class="signin-form-input" placeholder="输入手机号" type="number">
        <co-select slot="prepend" type="popup" searchPlaceholder="搜索" title="选择国家" v-model="countryCode" :data="countrys" class="signin-mobile-input">
          <template slot="selection" slot-scope="{ selects }">
            <span v-for="(item,index) in selects" :key="index">
              +{{ item.value }}
            </span>
          </template>
        </co-select>
      </co-input>
      <co-input v-model="code" @focus="focusIntoView" class="signin-form-input" placeholder="验证码" type="number">
        <co-button slot="append" class="sign-capthcha" :disabled="sended" @click="sendCode">
          {{ sendText }}
        </co-button>
      </co-input>
      <div v-if="agreement.length!=0" class="signin-argee">
        <span @click="argee=!argee" class="agree-check cenCen">
          <img v-if="!argee" src="https://img.alicdn.com/tfs/TB1gLM9Q7voK1RjSZFwXXciCFXa-200-200.png" />
          <img v-else src="https://img.alicdn.com/tfs/TB1fLM9Q7voK1RjSZFwXXciCFXa-200-200.png" />
        </span>
        <span class="signin-checkbox-label readAndAgree">
          我已仔细阅读并同意
        </span>
        <span class="signin-checkbox-label readAndAgree">
          <br />
          <br />
          <a target="_blank" style="  font-weight: bold;text-decoration: underline;" @click="openPage(item.agreementId)" class="label-link readAndAgree" ref="javascript:void(0);" v-for="(item,index) of agreement" :key="index" :style="[{color:$store.state.themeColor}]">《{{item.title}}》</a>
        </span>
      </div>
    </div>
    <div class="signin-submit-box">
      <co-button class="signin-submit" block color="primary" :disabled="!argee" :loading="signining" @click="submit">
        同意并登录
      </co-button>
    </div>
  </div>
</template>
<script>
import services from "../../api/profile";
import config from "../../config";
import areas from "../infoEntry/areaCode";
import { getLinkId } from "./../publicJs/getLinkId.js"; // 得到url 参数getLinkId并且赋值
// 接口服务
import buyTicketService from "./../../api/buyTicketService.js";

export default {
  data() {
    return {
      agreement: [], //协议
      argee: false,
      mobile: "",
      countryCode: "86",
      // countrys: areas.map(item => ({
      //   label: `${item.name} +${item.tel}`,
      //   value: item.tel
      // })),
      countrys: [
        {
          label: `中国 +86`,
          value: "86"
        }
      ],
      code: "",
      sendText: "获取验证码",
      sended: false,
      signining: false
    };
  },
  watch: {
    mobile() {
      if (this.mobile.length > 11) {
        this.$toast("请输入正确的手机号");
        this.mobile = this.mobile.substr(0, 11);
        return;
      }
      sessionStorage.setItem("signinMobile", this.mobile);
    },
    code() {
      if (this.code.length > 6) {
        this.code = this.code.substr(0, 6);
      }
    }
  },
  created() {
    if (sessionStorage.getItem("argee") === "true") {
      this.argee = true;
    }
    if (sessionStorage.getItem("signinMobile")) {
      this.mobile = sessionStorage.getItem("signinMobile");
    }

    this.initFun();
  },
  methods: {
    async initFun() {
      let agereeMents = [];
      if (sessionStorage.getItem("agereeMents")) {
        agereeMents = JSON.parse(sessionStorage.getItem("agereeMents"));
      }

      for (let i = 0; i < agereeMents.length; i++) {
        if (agereeMents[i].typeId == 2) {
          this.agreement.push(agereeMents[i]);
        }
      }
      if (this.agreement.length == 0) {
        // 如果没有本地数据则重新掉接口
        let res = await getLinkId();
        let linkId =
          this.$store.state.buyTicket.linkId ||
          sessionStorage.getItem("linkIdUcan") ||
          "";
        buyTicketService.getTicketList(linkId).then(res => {
          if (res.success && res.result.length) {
            for (let i = 0; i < res.result[0].agereeMents.length; i++) {
              if (res.result[0].agereeMents[i].typeId == 2) {
                this.agreement.push(res.result[0].agereeMents[i]);
              }
            }
          }
          if (this.agreement.length == 0) {
            this.$toast("请管理员创建登录协议");
            this.$router.push({
              name: "buyTicketHome"
            });
          }
        });
      }
      // buyTicketService
      //   .getAgreement({
      //     corpId: sessionStorage.getItem("corpIdUcan"),
      //     agereeId: sessionStorage.getItem("agereeIdNewWay")
      //   })
      //   .then(res => {
      //     //1 购票协议 2 登录协议 3 露脸协议
      //     if (res.success) {
      //       this.agreement = [];
      //       for (let i = 0; i < res.result.length; i++) {
      //         if (res.result[i].typeId == 2) {
      //           this.agreement.push(res.result[i]);
      //         }
      //       }
      //     }
      //   });
    },
    // 获取新的协议页面
    openPage(agreementId) {
      sessionStorage.setItem("argee", this.argee);
      buyTicketService.lookAgreement(agreementId).then(res => {
        if (res.success) {
          window.location.href = res.result;
        }
      });
    },
    focusIntoView(e) {
      const isAndroid =
        navigator.userAgent.toLowerCase().indexOf("android") !== -1;
      if (isAndroid) {
        this.timer = setTimeout(() => {
          e.target.scrollIntoView();
        }, 200);
      }
    },
    validMobile() {
      if (!this.mobile) {
        this.$toast("请输入手机号");
        return false;
      }
      return true;
    },
    validCode() {
      if (!this.code) {
        this.$toast("请输入验证码");
        return false;
      }
      return true;
    },
    countdown(count = 60) {
      if (count === 0) {
        this.sended = false;
        this.sendText = "重新发送";
        return;
      }
      this.sendText = `${count}s`;
      this.timer = setTimeout(() => {
        this.countdown(count - 1);
      }, 1000);
    },
    sendCode() {
      if (this.sended || !this.validMobile()) return;
      if (this.timer) clearTimeout(this.timer);
      this.sended = true;
      let activityId =
        this.$store.state.buyTicket.activityId ||
        sessionStorage.getItem("activityIdUcan") ||
        "";
      services
        .sendCode(this.mobile, this.countryCode, activityId)
        .then(() => {
          this.$toast("发送成功");
          this.countdown();
        })
        .catch(() => {
          this.sended = false;
          // this.$toast("发送失败");
        });
    },
    submit() {
      if (!this.validMobile() || !this.validCode()) return;
      this.signining = true;
      services
        .signin(this.mobile, this.countryCode, this.code)
        .then(res => {
          this.signining = false;
          if (this.$store.state.buyTicket.noSale) {
            if (
              sessionStorage.getItem("thisMobile") &&
              sessionStorage.getItem("thisMobile") != this.mobile
            ) {
              // 如果之前登录过，且是不同的手机号，则清除购物车
              this.$store.state.buyTicket.carTicketList = [];
              this.$store.state.buyTicket.carTicketSumList = [];
              this.$store.state.buyTicket.totalPrice = 0;
              this.$store.state.buyTicket.actualPrice = 0;
            }
            sessionStorage.setItem("thisMobile", this.mobile); //本地存储一下当前手机号，用于重新登录判断是否是同一手机号
            this.$router.push({
              name: "buyTicketHome"
            });
            // setTimeout(() => {
            //   this.$router.push({
            //     name: 'orderEnter'
            //   });
            // }, 100);
          } else {
            this.$router.replace("/profile");
          }
        })
        .catch(() => {
          this.signining = false;
        });
    }
  },
  beforeDestroy() {
    if (this.timer) clearTimeout(this.timer);
  }
};
</script>
<style lang="less">
.signin-page {
  padding-top: 108px;

  .ucan-image {
    width: 100%;
    display: block;
  }

  .alibaba-design {
    top: 30px;
  }

  .label-link {
    color: inherit;
    text-decoration: underline;
  }
}

.sign-capthcha {
  height: 100%;
  font-size: 24px;
  border-top-right-radius: 4px;
  border-bottom-right-radius: 4px;
  border-top-left-radius: 0;
  border-bottom-left-radius: 0;
}

.signin-form {
  margin-top: 68px;
}

.signin-form-input {
  height: 96px;
  border: none;
  padding: 0;
  background-color: rgba(0, 0, 0, 0.5);
  margin-bottom: 40px;
  border-radius: 4px;
  font-size: 24px;

  &::after {
    content: none;
  }
  .co-input__element {
    padding-left: 30px;
  }
  .co-input__prepend {
    margin-right: 0;
  }
}

.signin-mobile-input {
  font-size: 24px;
  position: relative;
  &::before {
    content: "";
    position: absolute;
    right: 0;
    height: 48px;
    top: 50%;
    margin-top: -24px;
    width: 1px;
    background-color: fade(#eee, 50%);
  }
  &::after {
    content: none;
  }
  .co-select__icon {
    display: none;
  }
}
.signin-argee {
  // display: flex;
  // justify-content: center;
  // align-items: center;
  width: 100%;
  height: auto;
  text-align: center;
  font-size: 24px;
  margin-top: 26px;
}

.signin-checkbox {
  width: 30px;
  height: 30px;
  display: inline-block;
  border: 1px solid fade(#fff, 60%); /*no*/
  border-radius: 50%;
  // position: relative;
  // display: flex;
  // justify-content: center;
  // align-items: center;
}

.signin-checkbox-check {
  font-size: 20px;
}
.signin-checkbox-label {
  margin-left: 20px;
  font-size: 22px;
  color: fade(#eee, 50%);
  cursor: pointer;
}

.signin-submit-box {
  position: absolute;
  left: 0;
  right: 0;
  bottom: 0;
}
.readAndAgree {
  font-size: 30px;
}
.agree-check {
  width: 35px;
  height: auto;
  display: inline-block;
  margin-right: 10px;
  cursor: pointer;
}
.agree-check > img {
  width: 100%;
  height: auto;
  margin-top: 6px;
}
</style>
